<script lang="ts">
export default {
  name: 'LabelingAbnormalStd'
}
</script>

<template>
  <q-page class="q-pa-md">
    <div class="row items-center">
      <div class="q-pb-md text-h5">{{ pageTitle }}</div>
      <q-space></q-space>
    </div>
    <q-banner class="text-white bg-red q-my-md" dense inline-actions v-if="serverErrorMessage">
      {{ serverErrorMessage }}
      <template v-slot:action>
        <q-btn @click="serverErrorMessage = ''" dense flat icon="close" size="sm" />
      </template>
    </q-banner>
    <div class="q-pa-sm shadow-2 q-mb-md items-center">
      <div class="row q-col-gutter-sm">
        <div class="col-12 col-sm-6 col-md-4 col-lg-3 row q-col-gutter-sm">
          <div class="col-4 text-right searchbar-label">栈板号</div>
          <div class="col-8">
            <easy-input v-model="$d.palletNo" />
          </div>
        </div>
        <div>
          <q-btn color="primary" label="解除异常" :disable="!$d.palletNo"  @click="removeLabelingAbnormal"
            :loading="removeLabelingAbnormalState"/>
        </div>
      </div>
    </div>

    <div class="q-pa-sm shadow-2">
      <div class="q-my-sm" v-if="fx.hasModifyRight('Wms.Inv.Inventory.ReportLabelingAbnormal')">每次上传的文件总共不要超过30MB！</div>
      <div :key="item" class="row q-mt-sm" v-for="(item, index) of $d.fileListToUpload">
        <div class="col-4">
          <input @change="controlUploadBtn" :ref="el => { if (el) UploadFiles[index] = el }" type="file">
        </div>
        <div class="col-8 row q-col-gutter-sm justify-end">
          <div style="width: 80%">
            <input :maxlength="100" placeholder="备注" :ref="el => { if (el) UploadComments[index] = el }" style="width: 100%;" type="text" class="inp">
          </div>
          <div>
            <q-btn :disable="doSubimtState" @click="removeFileForUpload(item, index)" color="red" label="移除" />
          </div>
        </div>
      </div>
      <div class="q-mt-sm">
        <q-btn :disable="doSubimtState || !$d.palletNo" @click="addFileForUpload" class="q-mr-sm" color="primary" icon="add"
               label="增加待上报文件" v-if="fx.hasModifyRight('Wms.Inv.Inventory.ReportLabelingAbnormal')" />
        <q-btn :disable="!isUploadReady || $d.fileListToUpload.length === 0 || !$d.palletNo" :loading="doSubimtState"
          @click="doUploadFiles" color="primary" icon="vertical_align_top" label="异常上报" v-if="fx.hasModifyRight('Wms.Inv.Inventory.ReportLabelingAbnormal')" />
      </div>
    </div>
  </q-page>
</template>

<script lang="ts" setup>
import {useTitleHelper} from '@njt/foundation/hooks/titleHelper'
import {reactive, Ref, ref} from 'vue'
import {uid} from 'quasar'

const pageTitle = '贴标异常上报/解除'
useTitleHelper(pageTitle)
// 上传状态
let doSubimtState = ref(false)
// 是否可上传
let isUploadReady = ref(false)

// 错误信息内容
let serverErrorMessage = ref('')
// 文件上传输入框
let UploadFiles:Ref<HTMLInputElement[]> = ref([])
// 文件备注输入框
let UploadComments:Ref<HTMLInputElement[]> = ref([])

let $d = reactive({
  // 栈板号
  palletNo: null as string | null,
  // 待上传文件列表
  fileListToUpload: [] as string[],
})

// 确保上传按钮是否可用
const controlUploadBtn = function () {
  let isReady = true
  if ($d.fileListToUpload.length === 0) {
    isReady = false
  } else {
    for (let i = 0; i < $d.fileListToUpload.length; i++) {
      if (!(UploadFiles.value[i]?.files![0])) {
        isReady = false
        break
      }
    }
  }
  isUploadReady.value = isReady
}

// 移除一个待上传
const removeFileForUpload = function (item: string, index: number) {
  $d.fileListToUpload.splice(index, 1)
  UploadFiles.value.splice(index, 1)
  controlUploadBtn()
}

// 新增一个待上传
const addFileForUpload = function () {
  let uuid = uid()
  $d.fileListToUpload.push(uuid)
  controlUploadBtn()
}

interface GetAccessoryResp {
  fileUuid: string | null,
  physicalUuid: string | null,
  storageClass: string | null,
  storageId: string | null,
  userName: string | null,
  userDispName: string | null,
  accessLevel: number,
  originalFileName: string | null,
  mimeType: string | null,
  fileSize: number,
  comment: string | null,
  internalFlag: string | null,
  createDt: Date,
  updateDt: Date
}
interface UploadResp {
  failedFiles: string | null
  succeededFiles: GetAccessoryResp[]
}
// 上传方法
const doUploadFiles = function () {
  // 检查文件总大小是否超过指定的尺寸
  let totalSize = 0
  for (let i = 0; i < $d.fileListToUpload.length; i++) {
    const file = UploadFiles.value[i]?.files![0]
    if (!file) {
      continue
    }
    totalSize += file.size
  }
  totalSize /= 1000 * 1000
  if (totalSize >= 30) {
    serverErrorMessage.value = '要上传的文件的总大小超过了30MB，请考虑分多次上传'
    return
  }

  serverErrorMessage.value = ''
  doSubimtState.value = true
  let formData = new window.FormData()
  for (let i = 0; i < $d.fileListToUpload.length; i++) {
    if ($d.palletNo) {
      formData.append('palletNo', $d.palletNo)
    }
    formData.append('abnormalReportFiles[' + String(i) + '].file', UploadFiles.value[i]!.files![0])
    formData.append('abnormalReportFiles[' + String(i) + '].comment', UploadComments.value[i].value)
  }
  $f.axios
    .post<UploadResp>('/project/mhlbc/inv/inventory/report-labeling-abnormal', formData)
    .then((resp) => {
      $d.fileListToUpload = []
      $f.ui.showNotifySucceeded( '栈板[' + $d.palletNo +']异常上报成功')
      $d.palletNo = null
    })
    .catch((err) => {
      serverErrorMessage.value = $f.getAxiosErrMsg(err)
    })
    .finally(() => {
      doSubimtState.value = false
    })
}

let removeLabelingAbnormalState = ref(false)
// 解除异常
const removeLabelingAbnormal = () => {
  serverErrorMessage.value = ''
  removeLabelingAbnormalState.value = true
  let params = {
    palletNo: $d.palletNo
  }
  $f.axios.post('/project/mhlbc/inv/inventory/remove-labeling-abnormal', params)
      .then(() => {
        $d.fileListToUpload = []
        $f.ui.showNotifySucceeded('栈板[' + $d.palletNo +']贴标异常解除')
        $d.palletNo = null
      })
      .catch((err) => {
        serverErrorMessage.value = $f.getAxiosErrMsg(err)
      })
      .finally(() => {
        removeLabelingAbnormalState.value = false
      })
}

const fx = $f
</script>
